// @flow
import React, { Component, Fragment, type Node } from 'react';
import cx from 'classnames';

import './Draggable.scss';

type Props = {
    id: string,
    draggType: string,
    isDraggable: boolean,
    draggingItems: Array<string>,
    draggingOverId?: string,
    children: Array<Node>,
    onNodeDragStart(id: string): void,
    onNodeDrag(e: any): void,
    onNodeDragEnter(id: string): void,
    onNodeDragLeave(id: string): void,
    onNodeDragEnd(id: string): void,
    onNodeDrop(id: string): void
};

class Draggable extends Component<Props> {
    itemRender = () => {
        const {
            id,
            draggType,
            draggingItems,
            isDraggable,
            draggingOverId,
            onNodeDragStart,
            onNodeDrag,
            onNodeDragEnter,
            onNodeDragLeave,
            onNodeDragEnd,
            onNodeDrop,
            children
        } = this.props;
        if (isDraggable) {
            return (
                <div
                    id={`draggable_${draggType}_${id}`}
                    className={cx('Draggable', {
                        isDragging: draggingItems.indexOf(id) !== -1,
                        dragOver: draggingOverId === id
                    })}
                    draggable="true"
                    onDragStart={e => {
                        e.dataTransfer.setData('id', e.target.id);
                        onNodeDragStart(e.target.id);
                    }}
                    onDrag={e => {
                        onNodeDrag(e);
                    }}
                    onDragOver={e => {
                        e.preventDefault();
                    }}
                    onDragEnter={e => {
                        onNodeDragEnter(e.target.id);
                    }}
                    onDragLeave={e => {
                        onNodeDragLeave(e.target.id);
                    }}
                    onDragEnd={e => {
                        e.dataTransfer.setData('id', '');
                        onNodeDragEnd(e.target.id);
                    }}
                    onDrop={e => {
                        // e.dataTransfer.setData("id", "");
                        onNodeDrop(e.target.id);
                    }}
                >
                    {children}
                </div>
            );
        } else {
            return (
                <div
                    id={`draggable_${id}`}
                    className={cx('Draggable', {
                        isDragging: draggingItems.indexOf(id) !== -1,
                        dragOver: draggingOverId === id
                    })}
                >
                    {children}
                </div>
            );
        }
    };
    render() {
        return <Fragment>{this.itemRender()}</Fragment>;
    }
}

export default Draggable;
